Page({
  data: {
    nvabarData: {
      title: '学生列表',
      transmit: ''
    },
    students: [],
    showModal: false,
    studentName: '',
    phone: '',
    avatarUrl: '',
    notes: '',
    status: '', // camera, preview, result
    watermarkedImagePath: '', // 带水印的照片路径
    location: '正在获取位置...', // 位置信息
    canvasWidth: 0,
    canvasHeight: 0,
  },

  onLoad: function () {
    // 加载学生数据
    this.loadStudentData();
  },

  onShow: function () {
    // 页面显示时刷新数据
    this.loadStudentData();
  },

  // 加载学生数据
  loadStudentData: function () {
    // 模拟数据 - 实际开发中应从服务器获取
    const students = [
      {
        id: 1,
        name: '张小萌',
        avatar: '',
        parentPhone: '138****5678',
        status: 'signed'
      },
      {
        id: 2,
        name: '李小明',
        avatar: '',
        parentPhone: '139****1234',
        status: 'unsigned'
      },
      {
        id: 3,
        name: '王小红',
        avatar: '',
        parentPhone: '136****8765',
        status: 'signed'
      },
      {
        id: 4,
        name: '赵小刚',
        avatar: '',
        parentPhone: '137****4321',
        status: 'signed'
      },
      {
        id: 5,
        name: '刘小华',
        avatar: '',
        parentPhone: '135****9876',
        status: 'unsigned'
      },
      {
        id: 6,
        name: '陈小丽',
        avatar: '',
        parentPhone: '134****3456',
        status: 'signed'
      },
      {
        id: 7,
        name: '杨小强',
        avatar: '',
        parentPhone: '133****6543',
        status: 'signed'
      },
      {
        id: 8,
        name: '黄小燕',
        avatar: '',
        parentPhone: '132****7890',
        status: 'signed'
      },
      {
        id: 9,
        name: '周小伟',
        avatar: '',
        parentPhone: '131****2345',
        status: 'unsigned'
      },
      {
        id: 10,
        name: '吴小芳',
        avatar: '',
        parentPhone: '130****6789',
        status: 'signed'
      },
      {
        id: 11,
        name: '阿三大三的',
        avatar: '',
        parentPhone: '130****6789',
        status: 'signed'
      },
    ];

    this.setData({
      students
    });
  },

  // 拨打电话
  makePhoneCall: function (e) {
    const phone = e.currentTarget.dataset.phone;

    wx.showModal({
      title: '拨打电话',
      content: `确定要拨打 ${phone} 吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: phone
          });
        }
      }
    });

    // 阻止事件冒泡，避免触发学生卡片点击事件
    e.stopPropagation();
  },

 
   // 显示签到弹窗
   addStudent: function(e) {
    const studentData = e.currentTarget.dataset.item || {};
    console.log(studentData)
    this.setData({
      showModal: true,
      studentName: studentData.name || '',
      phone: studentData.parentPhone || '',
      avatarUrl:''
    });
     // 确保动画生效
     setTimeout(() => {
      this.setData({
        showModal: true
      });
    }, 50);
  },

  // 隐藏弹窗
  hideModal: function() {
    this.setData({
      showModal: false
    });
  },

  // 输入事件处理
  onNameInput: function(e) {
    this.setData({
      studentName: e.detail.value
    });
  },

  onPhoneInput: function(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  onNotesInput: function(e) {
    this.setData({
      notes: e.detail.value
    });
  },


  // 确认保存
  confirmEdit: function() {
    const { studentName, phone, avatarUrl, notes } = this.data;
    
    // 简单验证
    if (!studentName.trim()) {
      wx.showToast({
        title: '请输入学生姓名',
        icon: 'none'
      });
      return;
    }
    
    if (!phone.trim()) {
      wx.showToast({
        title: '请输入联系方式',
        icon: 'none'
      });
      return;
    }

    if (!avatarUrl) {
      wx.showToast({
        title: '请拍摄学生照片',
        icon: 'none'
      });
      return;
    }
    
    // 构建学生数据对象
    const studentData = {
      name: studentName,
      phone: phone,
      avatar: avatarUrl,
      notes: notes
    };
    
    // 这里可以添加保存到服务器的逻辑
    console.log('保存学生信息:', studentData);
    
    // 隐藏弹窗
    this.hideModal();
    
    wx.showToast({
      title: '保存成功',
      icon: 'success'
    });
  },

  // 显示拍照页面
  showCameraPage() {
    this.getLocation(); // 定位
    this.setData({
      showCamera:true,
      status: 'camera'
    })
  },
  // 获取地理位置
  getLocation: function () {
    const that = this;

    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        const { latitude, longitude } = res;
        // 使用腾讯地图逆地理编码（需要申请密钥）
        that.reverseGeocoder(latitude, longitude);
      },
      fail: function (err) {
        console.error('获取位置失败:', err);
        that.setData({
          location: '位置获取失败'
        });
      }
    });
  },

  // 逆地理编码获取具体地址
  reverseGeocoder: function (latitude, longitude) {
    const that = this;
    // 注意：这里需要替换为你自己的腾讯地图密钥
    const key = 'YOUR_TENCENT_MAP_KEY';

    wx.request({
      url: 'https://apis.map.qq.com/ws/geocoder/v1/',
      data: {
        location: `${latitude},${longitude}`,
        key: key,
        output: 'json'
      },
      success: function (res) {
        if (res.data.status === 0) {
          const address = res.data.result.address;
          that.setData({
            location: address
          });
        } else {
          that.setData({
            location: '位置解析失败'
          });
        }
      },
      fail: function () {
        that.setData({
          location: '位置服务异常'
        });
      }
    });
  },

  // 拍照
  takePhoto: function () {
    const that = this;
    const ctx = wx.createCameraContext();

    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          status: 'preview',
        })
        wx.showLoading({
          title: '',
          icon: 'none'
        })
        that.addLogo(res.tempImagePath)
      },
      fail: (err) => {
        console.error('拍照失败:', err);
        wx.showToast({
          title: '拍照失败',
          icon: 'none'
        });
      }
    });
  },

  confirmPhoto() {
    this.setData({
      avatarUrl: this.data.watermarkedImagePath,
    }, () => {
      this.setData({
        status: '',
        watermarkedImagePath: '',
        showCamera:false
      });
    });

  },

  // 确定照片，添加水印
  addLogo: function (tempImagePath) {
    const that = this;
   

    wx.getImageInfo({
      src: tempImagePath,
      success: function (res) {
        const { width, height } = res;
        that.setData({
          canvasWidth: width,
          canvasHeight: height
        }, () => {
          // 确保canvas尺寸设置完成后绘制水印
          setTimeout(() => {
            that.drawWatermark(width, height, tempImagePath);
          }, 100);
        });
      },
      fail: function (err) {
        console.error('获取图片信息失败:', err);
        wx.hideLoading()
        wx.showToast({
          title: '图片处理失败',
          icon: 'none'
        });
      }
    });
  },

  // 绘制水印
  drawWatermark: function (width, height, tempImagePath) {
    const that = this;
    const ctx = wx.createCanvasContext('watermarkCanvas');

    // 1. 绘制原图
    ctx.drawImage(tempImagePath, 0, 0, width, height);

    // 2. 准备水印信息
    const now = new Date();
    const dateStr = now.toLocaleDateString('zh-CN');
    const timeStr = now.toLocaleTimeString('zh-CN', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
    const weekDay = `星期${weekDays[now.getDay()]}`;
    const location = that.data.location;

    // 3. 水印文字
    const watermarkText = `${timeStr} ${dateStr} ${weekDay} ${location}`;

    // 4. 设置水印样式
    const fontSize = Math.max(16, width * 0.02); // 自适应字体大小
    ctx.setFontSize(fontSize);

    // 测量文字宽度
    const textWidth = ctx.measureText(watermarkText).width;
    const padding = fontSize;

    // 5. 绘制水印背景（半透明黑色）
    ctx.setFillStyle('rgba(0, 0, 0, 0.5)');
    const bgWidth = textWidth + padding * 2;
    const bgHeight = fontSize * 1.8;
    const bgX = width - bgWidth - 20; // 右上角位置
    const bgY = height - bgHeight - 20;
    ctx.fillRect(bgX, bgY, bgWidth, bgHeight);

    // 6. 绘制水印文字
    ctx.setFillStyle('rgba(255, 255, 255, 0.9)');
    ctx.setTextBaseline('middle');
    ctx.fillText(watermarkText, bgX + padding, bgY + bgHeight / 2);

    // 7. 绘制完成
    ctx.draw(false, function () {
      // 将canvas内容导出为图片
      wx.canvasToTempFilePath({
        canvasId: 'watermarkCanvas',
        success: function (res) {
          that.setData({
            watermarkedImagePath: res.tempFilePath,
         
          });
          wx.hideLoading()
        },
        fail: function (err) {
          console.error('导出水印图片失败:', err);
          wx.hideLoading()
          wx.showToast({
            title: '生成水印失败',
            icon: 'none'
          });
        }
      });
    });
  },

   // 相机错误处理
   cameraError: function (err) {
    console.error('相机错误:', err);
    wx.showToast({
      title: '相机启动失败',
      icon: 'none'
    });
  },
  // 重新拍照
  cancelPhoto: function () {
    this.setData({
      status: '',
      watermarkedImagePath: ''
    });
  },
 // 取消照片
 cancelPhoto: function () {
  this.setData({
    status: '',
    watermarkedImagePath: '',
    showCamera:false
  });
},
  // 重新拍照
  retakePhoto: function () {
    this.setData({
      status: 'camera',
      watermarkedImagePath: '',
    });
  },


 
});